<template>
    <div class="light-Ct" :class="{
        'light-Ct-line': parentChildrenLength && parentChildrenLength > 1 || (parentChildrenLength && parentChildrenLength > 2 && item.children && item.children.length > 2)
    }" @click="hideToolbar">

        <div class="item-Box" @click="selectNode(index, item)" @contextmenu.prevent="showToolbar($event, index, item)">

            <div class="item-Cd-border" :class="{ 'selected': isSelected }">
                <div class="item-Cd" :class="{ 'item-Cd-line': item.children && item.children.length > 0 }">
                    <div class="item-Cd-title" :style="item?.styles" :class="{
                        'shape2': item?.styles?.shape == 2,
                        'shape3': item?.styles?.shape == 3,
                    }">
                        <div style="display: flex;align-items: center;width: 100%;">
                            <div class="light-circle" style="position: relative;" :class="{
                                'light-green': item.nodeState == 1,
                                'light-red': item.nodeState == 0,
                                'light-orange': item.nodeState == 2,
                            }">
                                <span class="circleTit"> {{ item.percent }} </span>
                            </div>
                            <div class="item-name" :class="{ 'highlight': isHighlighted(item) }">
                                <div v-if="!isEditing" @click.stop="selectNode(index, item), startEdit()"
                                    class="pointers" style="display: inline-block;">
                                    {{ item.name }}</div>
                                <el-input v-else v-model="editedName" @blur="finishEdit" @keyup.enter="finishEdit"
                                    ref="editInput" style="width: 150px;" />
                            </div>
                            <div class="operation">
                                <a @click="addBrotherItem(index, item)" v-if="item.firstLevel !== true" title="同级 +">
                                    <el-icon>
                                        <ArrowDownBold />
                                    </el-icon>
                                </a>
                                <span v-if="item.firstLevel !== true">|</span>
                                <a @click="addChildItem(index, item)" title="子级 + ">
                                    <el-icon>
                                        <ArrowRightBold />
                                    </el-icon>
                                </a>
                                <span>|</span>
                                <a @click="addChildNestedItem(index, item)" title="子级 + ">
                                    <el-icon>
                                        <DArrowRight />
                                    </el-icon>
                                </a>
                                <span>|</span>
                                <a @click="testIntem(index, item)" title="编辑">
                                    <el-icon>
                                        <EditPen />
                                    </el-icon>
                                </a>
                                <span>|</span>
                                <a @click="deleteItem(index, item)" title="删除">
                                    <el-icon>
                                        <DeleteFilled />
                                    </el-icon>
                                </a>
                                <span>|</span>
                                <a @click="copyItem(index, item)" title="复制">
                                    <el-icon>
                                        <DocumentCopy />
                                    </el-icon>
                                </a>
                                <span>|</span>
                                <a @click="pasteItem(index, item)" title="粘贴">
                                    <el-icon>
                                        <DocumentRemove />
                                    </el-icon>
                                </a>
                                <span>|</span>
                                <a @click="seeNodeDetail(index, item)" title="反馈信息">
                                    <el-icon>
                                        <ChatDotSquare />
                                    </el-icon>
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- <div>子{{ item.id }}</div>
            <div>父{{ item.parentId }}</div> -->

            <div v-if="item.children.length > 0" class="item-chNum" :class="{ 'item-chNum-hov': item.expanded }"
                @click="expandCollapse(index, item)">
                {{ item.expanded ? '-' : item.children.length }}
            </div>
        </div>

        <!-- 工具栏 -->
        <OperToolbar :item="item" v-if="toolbarVisible"
            :style="{ top: `${toolbarPosition.top}px`, left: `${toolbarPosition.left}px` }"
            @updateStyle="updateStyle" />

        <div style="display: flex;align-items: center;justify-content: center;">
            <!-- v-if="item.expanded && item.children && item.children.length" -->
            <Draggable :list="item.children" :key="item.id" :group="{ name: 'items', pull: true, put: true }"
                @end="dragEnd" :move="onMove" item-key="id" v-if="item.expanded"
                :class="['childItem', item.children && item.children.length ? 'childItemSon' : 'noChildItem']"
                ghost-class="ghost" chosen-class="chosen" animation="300" forceFallback="true" :handle="'.item-name'">
                <template v-slot:item="{ element }">
                    <RecursiveItemHX :item="element" :index="index" :lightsItem="lightsItem" @editItem="editItem"
                        @deleteItem="deleteItem" @addBrotherItem="addBrotherItem" @addChildItem="addChildItem"
                        @testIntem="testIntem" @seeNodeDetail="seeNodeDetail" @expandCollapse="expandCollapse"
                        :parentChildrenLength="item.children.length" @addChildNestedItem="addChildNestedItem"
                        @updateTree="updateTree" @copyItem="copyItem" @pasteItem="pasteItem"
                        :nodeSearHighLight="nodeSearHighLight" @selectNode="selectNode" :selectedItem="selectedItem" />
                </template>
                <template v-slot:empty>
                    <div></div>
                </template>
            </Draggable>
        </div>

    </div>
</template>

<script setup>
import { ref, onMounted, defineProps, defineEmits, onUnmounted, nextTick, watch, computed } from 'vue';
import RecursiveItemHX from './RecursiveItemHX';
import { ArrowRightBold, ArrowDownBold, EditPen, DeleteFilled, ChatDotSquare, DArrowRight, DocumentCopy, DocumentRemove } from '@element-plus/icons-vue';
import OperToolbar from '@/components/OperToolbar.vue';
// import { ElMessage } from 'element-plus';
import Draggable from 'vuedraggable'

const props = defineProps({
    item: {
        type: Object,
        required: true
    },
    index: {
        type: Number,
        required: true
    },
    parentChildrenLength: { // 新增 prop
        type: Number,
        default: 0
    },
    popoverPlacement: {
        type: String,
        default: 'right'
    },
    lightsItem: { // 所有的节点数据
        type: Array,
        default: () => []
    },
    nodeSearHighLight: { // 搜索高亮
        type: String,
        default: ''
    },
    selectedItem: {  // 新增的选中节点 prop
        type: Object,
        default: null,
    },
});

const emit = defineEmits(['testIntem', 'editItem', 'addBrotherItem', 'addChildItem', 'deleteItem', 'seeNodeDetail', 'expandCollapse', 'addChildNestedItem', 'updateTree', 'copyItem', 'pasteItem', 'selectNode']);

const isEditing = ref(false);
const editedName = ref(props.item.name);
const editInput = ref(null);

watch(() => props.item, (newItem) => {
    if (newItem) {
        editedName.value = newItem.name === 'A' ? '' : newItem.name;
    }
},
    { immediate: true }
);

const startEdit = () => {
    if (isSelected.value) {
        isEditing.value = true;
        nextTick(() => {
            if (isEditing.value && editInput.value) {
                editInput.value.focus();
            }
        });
    }
};

const finishEdit = () => {
    isEditing.value = false;
    if (!editedName.value) {
        return; // ElMessage.error("请输入节点名称");
    }
    if (editedName.value !== props.item.name) {
        emit('editItem', props.index, { ...props.item, name: editedName.value });
    }
};

const dragEnd = (event) => {
    console.log("结束dragEnd：", event);
    const { oldIndex, newIndex } = event;
    if (oldIndex !== undefined && newIndex !== undefined) {
        // const movedItem = props.item.children[oldIndex];
        // console.log("移动的项数据：", movedItem);
        const data = setParentIdToChildren(props.lightsItem);
        updateTree(oldIndex, newIndex, data)

    } else {
        console.warn("拖拽结束时，索引未定义，无法更新树形结构！");
    }
};

// 不同级数据拖拽，parentId值取上一级的id
const setParentIdToChildren = (items, parentId = null) => {
    items.forEach(item => {
        item.parentId = parentId;
        if (item.children && item.children.length > 0) {
            setParentIdToChildren(item.children, item.id);
        }
    });

    return items;
};
// 更新外部数据
const updateTree = (oldIndex, newIndex, updatedItems) => {
    console.log("updateTree", oldIndex, newIndex, updatedItems);
    emit('updateTree', oldIndex, newIndex, updatedItems);
};

const onMove = (event) => {
    console.log("起始位置:", event.from);
    console.log("目标位置:", event.to);
    console.log("移动的项event:", event);
    // if (event.from === event.to) {
    return true; // 允许在同一容器中拖动
    // } else {
    //     console.warn('只能在同级节点之间移动');
    //     // 可以弹出错误提示，或返回 false 来阻止移动
    //     return false;
    // }
};

const testIntem = (index, item) => {
    emit('testIntem', index, item);
};

const editItem = (index, item) => {
    emit('editItem', index, item);
};

const addBrotherItem = (index, item) => {
    emit('addBrotherItem', index, item);
};

const addChildItem = (index, item) => {
    emit('addChildItem', index, item);
};

const deleteItem = (index, item) => {
    emit('deleteItem', index, item);
};

const seeNodeDetail = (index, item) => {
    emit('seeNodeDetail', index, item)
};

const expandCollapse = (index, item) => {
    emit('expandCollapse', index, item);
};

const addChildNestedItem = (index, item) => {
    emit('addChildNestedItem', index, item);
};

const copyItem = (index, item) => {
    emit('copyItem', index, item);
};

const pasteItem = (index, item) => {
    emit('pasteItem', index, item);
};

const isHighlighted = (item) => {
    if (!props.nodeSearHighLight) {
        return false;
    }
    if (props.nodeSearHighLight && item.name.includes(props.nodeSearHighLight)) {
        return true;
    }
    if (item.children && item.children.length > 0) {
        return item.children.some(child => isHighlighted(child));
    }
    return false;
};

const isSelected = computed(() => {
    // 如果 selectedItem 为 null 或者不匹配当前项，表示当前节点未被选中
    return props.selectedItem?.id === props.item.id;
});

const selectNode = (index, item) => {
    // nextTick(() => {
    //     if (isSelected.value) {
    //         emit('selectNode',index, null);  // 取消选中，传递 null
    //     } else {
    emit('selectNode', index, item);  // 否则选中该项
    //     }
    // });
};

onMounted(() => {

});

onUnmounted(() => {
    editInput.value = null;
});


const toolbarVisible = ref(false); // 工具栏是否显示
const toolbarPosition = ref({ top: 0, left: 0 }); // 工具栏的位置

watch(() => props.selectedItem, (newItem) => {
    toolbarVisible.value = newItem?.id === props.item.id;
});

const showToolbar = (event, index, item) => {
    toolbarPosition.value = {
        top: event.clientY,
        left: event.clientX,
    };
    toolbarVisible.value = true;
    emit('selectNode', index, item);
};

const hideToolbar = (event) => {
    if (event.target.closest('.toolbarBox') || event.target.closest('.el-select-dropdown') || event.target.closest('.el-color-picker')) {
        return;
    }
    toolbarVisible.value = false;
};

const updateStyle = (style) => {
    console.log("updateStyle：", style);
    emit('editItem', null, style);
};

</script>

<style lang="scss" scoped>
.pointers {
    cursor: pointer;
}

// 纵向样式
.light-item {

    .light-Ct {
        display: flex;
        align-items: center;

        .item-Box {
            position: relative;
            padding-right: 20px;
            box-sizing: border-box;
            transition: all 0.3s ease;

            .item-chNum {
                z-index: 99;
                position: absolute;
                right: 0px;
                top: 50%;
                margin-top: -8px;
                font-size: 12px;
                color: var(--global-font-color);
                border-radius: 50%;
                padding: 0px;
                min-width: 16px;
                height: 16px;
                line-height: 16px;
                cursor: pointer;
                border: 1px solid rgb(43, 38, 38);
                background: #fff;

                &.item-chNum-hov {
                    display: none;
                }
            }

            .item-Cd-border {
                padding: 2px 4px;
                border-radius: 5px;
                box-sizing: border-box;
                border: 2px solid transparent;
                transition: border-color 0.2s ease;
            }

            .operation {
                background-color: #fff;
                border: 1px solid #ddd;
                padding: 8px;
                border-radius: 0px 4px 4px 0px;
                box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
                display: none;
                margin-left: 10px;
                font-size: 14px;
                width: max-content;

                &:hover {
                    display: block;
                }

                a {
                    color: var(--global-link-color);
                    text-decoration: none;
                    cursor: pointer;
                    display: inline-block;
                }

                span {
                    margin: 0px 4px;
                    color: #ccc;
                    display: inline-block;
                }
            }


            &:hover {
                .item-chNum {
                    &.item-chNum-hov {
                        display: block;
                    }
                }

                .item-Cd-border {
                    border-color: darkseagreen;
                }

                .operation {
                    display: block;
                }

                .item-Cd-title {
                    padding-right: 0px;
                }
            }
        }

        .item-Cd {
            // padding: 4px 8px;
            // border: 1px solid #ddd;
            border-radius: 5px;
            // background-color: #f9f9f9;
            transition: background-color 0.3s;
            position: relative;

            &.item-Cd-line::after {
                content: "";
                position: absolute;
                right: -26px;
                top: 50%;
                width: 25px;
                height: 1px;
                background-color: rgb(43, 38, 38);
            }

            &:hover {
                background-color: #eee;
            }

            .item-Cd-title {
                display: flex;
                align-items: center;
                flex-wrap: wrap;
                min-height: 34px;
                background-color: #E4E7ED;
                border-radius: 4px;
                padding-right: 10px;
                box-sizing: border-box;
                color: var(--global-font-color);
                font-size: var(--global-font-size);

                &.shape2 {
                    display: inline-block;
                    clip-path: polygon(50% 0%, 100% 50%, 50% 100%, 0% 50%);
                    background-color: #ddd;
                    padding: 24px;
                }

                &.shape3 {
                    border-radius: 30px;
                }

                .light-circle {
                    width: 12px;
                    height: 12px;
                    line-height: 30px;
                    text-align: center;
                    border-radius: 50%;
                    margin-right: 4px;
                    color: white;

                    &.light-green {
                        background-color: green;
                    }

                    &.light-red {
                        background-color: red;
                    }

                    &.light-orange {
                        background-color: orange;
                    }

                    .circleTit {
                        position: absolute;
                        top: -40px;
                        left: 0px;
                        font-weight: bold;
                        color: black;
                    }
                }
            }

            .item-name {
                width: max-content;
                text-align: left;
            }
        }

        .childItem {
            margin-left: 24px;
            position: relative;

            .light-Ct {
                position: relative;
            }


            .light-Ct-line::after {
                content: "";
                position: absolute;
                left: -24px;
                top: 0px;
                width: 1px;
                height: calc(100% + 2px);
                background-color: rgb(43, 38, 38);
            }

            >.light-Ct-line:first-child::after {
                content: "";
                position: absolute;
                left: -24px;
                top: 50%;
                width: 1px;
                height: calc(50% + 2px);
                background-color: rgb(43, 38, 38);
            }

            >.light-Ct-line:last-child::after {
                content: "";
                position: absolute;
                left: -24px;
                top: 0px;
                width: 1px;
                height: 50%;
                background-color: rgb(43, 38, 38);
            }


            &.noChildItem {
                width: 80px;
                height: 36px;
                // background: pink;
                margin-left: -14px;
            }
        }

        .childItemSon {
            // padding-left: 24px;

            &>.light-Ct::before {
                content: "";
                position: absolute;
                left: -24px;
                top: 50%;
                width: 30px;
                height: 1px;
                background-color: black;
            }
        }
    }
}

.item-info {
    text-align: left;
    line-height: 20px;
    color: var(--global-font-color);
    font-size: var(--global-font-size);

    p {
        margin: 0px;
    }
}

.light-wrapHXRL {

    .item-name .pointers,
    .circleTit,
    .el-input,
    .item-chNum {
        transform: rotate(180deg) scaleY(-1);
    }
}

::v-deep .ghost {
    &.light-Ct::before {
        // display: none !important;
    }

    &.light-Ct-line::after {
        display: none !important;
    }
}

::v-deep .chosen {
    &.light-Ct::before {
        // display: none !important;
    }

    &.light-Ct-line::after {
        display: none !important;
    }
}

.highlight {
    background-color: yellow !important;
    font-weight: bold !important;
}

.selected {
    border: 2px solid #1e61ff !important;
}
</style>
